# middleware.py
from django.http import JsonResponse
from base_utils.exception import BaseError  # 导入你的异常基类
from base_utils.response_http_code import SuccessStatus, ServerErrorStatus, ForbiddenStatus
from base_utils.response_fmt import get_response_dict


# 中间件捕获自定义异常类,在请求函数中抛出异常时，可以直接捕获响应
class CustomExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_exception(self, request, exception):
        """处理视图函数中抛出的异常"""
        if isinstance(exception, BaseError):
            # 构建标准的错误响应
            error_data = get_response_dict(exception.http_code, exception.msg)
            if exception.http_code == ServerErrorStatus.http_code:
                # 系统内部错误，是状态码是400
                return JsonResponse(error_data, status=exception.http_code)
            else:
                # 对于其他的异常都是，状态码都是200
                return JsonResponse(error_data, status=SuccessStatus.http_code)

        # 非自定义异常继续向上抛出，由Django默认处理
        return None

"""
MIDDLEWARE = [
    "base_middles.exception_middle.CustomExceptionMiddleware",
]
"""